package com.getpebble.android.jskit.webapps;

import android.webkit.JavascriptInterface;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.jskit.bridge.DeviceBridge;
import com.getpebble.android.jskit.concurrency.JsThreadPools;
import com.getpebble.android.jskit.webapps.JsKit.WebviewClientPack;
import com.getpebble.android.jskit.webapps.JsKit.WebviewClientPack.WebappProcessState;
import com.getpebble.android.jskit.webapps.PebbleBabel.AppInfoBlocks;
import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class JsKitAccessor {
    public static final String TAG = "JsKitAccessor";
    protected final WeakReference<WebappRunHost> mHostedAndroidWebappRef;
    protected AppInfoBlocks mRegisteredJavascriptAppinfo;

    @JavascriptInterface
    public int getVersionCode() {
        return JsKit.jsKitAccess().getVersionCode();
    }

    @JavascriptInterface
    public void showSimpleNotificationOnPebble(String title, String notificationText) {
        JsKit.jsKitAccess().showSimpleNotificationOnPebble(title, notificationText);
    }

    @JavascriptInterface
    public String getAccountToken() {
        return JsKit.jsKitAccess().getAccountToken(hostedWebappCallerIdString());
    }

    @JavascriptInterface
    public String getWatchToken() {
        return JsKit.jsKitAccess().getWatchToken(hostedWebappCallerIdString());
    }

    @JavascriptInterface
    public String openURL(String url) {
        return loadURL(url);
    }

    public JsKitAccessor(WebappRunHost hostedAndroidWebapp) {
        this.mRegisteredJavascriptAppinfo = new AppInfoBlocks();
        this.mHostedAndroidWebappRef = new WeakReference(hostedAndroidWebapp);
        JsKit.jsKitAccess().registerWebclient(hostedAndroidWebapp);
    }

    public JsKitAccessor() {
        this.mRegisteredJavascriptAppinfo = new AppInfoBlocks();
        this.mHostedAndroidWebappRef = new WeakReference(null);
    }

    public UUID hostedWebappCallerId() {
        WebappRunHost f = (WebappRunHost) this.mHostedAndroidWebappRef.get();
        if (f != null) {
            return f.clientUuid();
        }
        return null;
    }

    public String hostedWebappCallerIdString() {
        WebappRunHost f = (WebappRunHost) this.mHostedAndroidWebappRef.get();
        if (f != null) {
            return f.clientUuidAsString();
        }
        return null;
    }

    @JavascriptInterface
    public String registerJavascriptAppinfo(String appInfoJsonString) {
        String str;
        String str2 = "[%s::%s] : appInfoJsonString: %s";
        Object[] objArr = new Object[3];
        objArr[0] = JsKit.class.getSimpleName();
        objArr[1] = this.mRegisteredJavascriptAppinfo;
        if (appInfoJsonString == null) {
            str = "null";
        } else {
            str = appInfoJsonString;
        }
        objArr[2] = str;
        PebbleWebappBaseActivity.LogSimpleDebug(str2, objArr);
        long detectAppKeyChange = this.mRegisteredJavascriptAppinfo.keysUpdateSerial;
        this.mRegisteredJavascriptAppinfo = PebbleBabel.appendNewDataToAppInfoBlocks(this.mRegisteredJavascriptAppinfo, appInfoJsonString);
        String newRegisteredJsAppUuidString = null;
        if (detectAppKeyChange != this.mRegisteredJavascriptAppinfo.keysUpdateSerial) {
            PebbleBabel translatorSpecificToMyClient = JsKit.jsKitAccess().getMessageTranslatorForClient(hostedWebappCallerIdString());
            if (translatorSpecificToMyClient != null) {
                translatorSpecificToMyClient.addAppMappingsFromInnerKeysSubblock(this.mRegisteredJavascriptAppinfo.keysMapBlock);
                translatorSpecificToMyClient.updateActiveAppUuidToAppUuidInsideTheBlock(this.mRegisteredJavascriptAppinfo);
                try {
                    newRegisteredJsAppUuidString = this.mRegisteredJavascriptAppinfo.infoBlock.optString("uuid", null);
                } catch (Exception e) {
                    Trace.debug(TAG, "registerJavascriptAppinfo", e);
                }
            }
        }
        JsKit.jsKitAccess().registerJavascriptAppinfo(hostedWebappCallerIdString(), appInfoJsonString, newRegisteredJsAppUuidString);
        return newRegisteredJsAppUuidString;
    }

    public void signalWebappRunHostOnCreate() {
        JsKit.jsKitAccess().changeSelfWebappProcessState(hostedWebappCallerIdString(), WebappProcessState.Created);
    }

    public void signalWebappRunHostOnDestroy(boolean isOnDestroyTheFullTeardown) {
        JsKit.jsKitAccess().signalWebappRunHostOnDestroy(hostedWebappCallerIdString(), isOnDestroyTheFullTeardown);
    }

    public void signalWebappRunHostOnPause() {
        JsKit.jsKitAccess().changeSelfWebappProcessState(hostedWebappCallerIdString(), WebappProcessState.Paused);
    }

    public void signalWebappRunHostOnResume() {
        JsKit.jsKitAccess().changeSelfWebappProcessState(hostedWebappCallerIdString(), WebappProcessState.Running);
    }

    public void signalWebappRunHostOnStop() {
    }

    public void signalWebappRunHostOnStart() {
    }

    @JavascriptInterface
    public void showToast(String toast) {
        JsKit.jsKitAccess().showToast(toast);
    }

    @JavascriptInterface
    public void executeHttp(String tag) {
        JsKit.jsKitAccess().executeHttp(tag);
    }

    @JavascriptInterface
    public void jsTimerTriggered(String timerContextData) {
        JsKit.jsKitAccess().jsTimerTriggered(hostedWebappCallerIdString(), timerContextData);
    }

    @JavascriptInterface
    public String httpGetInitiate(String url, String jsonObjectStringCustomAddedHeaders, String replyTag) {
        return JsKit.jsKitAccess().httpGetInitiate(hostedWebappCallerIdString(), url, jsonObjectStringCustomAddedHeaders, replyTag);
    }

    @JavascriptInterface
    public String httpPostInitiateKeyValueData(String url, String jsonObjectStringCustomAddedHeaders, String jsonObjectStringDataKVPairs, String replyTag) {
        return JsKit.jsKitAccess().httpPostInitiateKeyValueData(hostedWebappCallerIdString(), url, jsonObjectStringCustomAddedHeaders, jsonObjectStringDataKVPairs, replyTag);
    }

    @JavascriptInterface
    public String httpPostInitiateBodyAsData(String url, String jsonObjectStringCustomAddedHeaders, String bodyData, String replyTag) {
        return JsKit.jsKitAccess().httpPostInitiateBodyAsData(hostedWebappCallerIdString(), url, jsonObjectStringCustomAddedHeaders, bodyData, replyTag);
    }

    @JavascriptInterface
    public void showNotificationOnPebble(String jsonObjectStringNotificationData) {
        JsKit.jsKitAccess().showNotificationOnPebble(jsonObjectStringNotificationData);
    }

    @JavascriptInterface
    public void sendStartWatchAppMessage() {
        JsKit.jsKitAccess().sendStartWatchAppMessage(hostedWebappCallerIdString());
    }

    @JavascriptInterface
    public void sendStartWatchAppMessage(String deliberatelyOverriddenWatchAppUuidString) {
        JsKit.jsKitAccess().sendStartWatchAppMessage(hostedWebappCallerIdString(), deliberatelyOverriddenWatchAppUuidString);
    }

    @JavascriptInterface
    public String sendAppMessageString(String appUuidString, String jsonObjectString) {
        Trace.debug(TAG, "sendAppMessageString");
        return JsKit.jsKitAccess().sendAppMessage(hostedWebappCallerIdString(), appUuidString, jsonObjectString);
    }

    @JavascriptInterface
    public String sendAppMessageString(String jsonObjectString) {
        return sendAppMessageString(null, jsonObjectString);
    }

    @JavascriptInterface
    public String getExtensions() {
        return JsKit.jsKitAccess().getExtensions();
    }

    protected static Map<String, List<String>> getUrlParameters(String url) throws UnsupportedEncodingException {
        Map<String, List<String>> params = new HashMap();
        String[] urlParts = url.split("\\?");
        if (urlParts.length > 1) {
            for (String param : urlParts[1].split("&")) {
                String[] pair = param.split("=", 2);
                String key = URLDecoder.decode(pair[0], "UTF-8");
                String value = "";
                if (pair.length > 1) {
                    value = URLDecoder.decode(pair[1], "UTF-8");
                }
                List<String> values = (List) params.get(key);
                if (values == null) {
                    values = new ArrayList();
                    params.put(key, values);
                }
                values.add(value);
            }
        }
        return params;
    }

    @JavascriptInterface
    public void startupScriptHasLoaded(String url) {
        String extraDataForLoading = null;
        try {
            List<String> params = (List) getUrlParameters(new URL(url).toString()).get("params");
            if (params != null && params.size() > 0) {
                extraDataForLoading = (String) params.get(0);
            }
        } catch (Exception e) {
            Trace.debug(TAG, "startupScriptHasLoaded", e);
        }
        final WebappRunHost f = (WebappRunHost) this.mHostedAndroidWebappRef.get();
        if (f != null) {
            final String extraDataForLoadingParam = extraDataForLoading;
            JsThreadPools.MainWorkerThreadsExecutorService().execute(new Runnable() {
                public void run() {
                    f.onBootstrapScriptLoadedAndReady(extraDataForLoadingParam);
                }
            });
        }
        JsKit.jsKitAccess().startupScriptHasLoaded(hostedWebappCallerIdString(), url, true);
    }

    @JavascriptInterface
    public void signalAppScriptLoadedByBootstrap(boolean externalRegisterWebappNeeded) {
        String newRegisteredJsAppUuidString = null;
        if (externalRegisterWebappNeeded) {
            try {
                NoUiWebappBase appRef = (NoUiWebappBase) this.mHostedAndroidWebappRef.get();
                if (appRef != null) {
                    newRegisteredJsAppUuidString = registerJavascriptAppinfo(appRef.loadAppInfoJsonAsString());
                }
            } catch (Exception e) {
                Trace.debug(TAG, "signalAppScriptLoadedByBootstrap", e);
            }
        }
        if (newRegisteredJsAppUuidString == null) {
            UUID newRegisteredJsAppUuid = JsKit.jsKitAccess().currentActiveAppUuid(hostedWebappCallerIdString());
            if (newRegisteredJsAppUuid != null) {
                newRegisteredJsAppUuidString = newRegisteredJsAppUuid.toString();
            }
        }
        final DeviceBridge bridge = DeviceBridge.getInstance();
        if (bridge.isConnected()) {
            try {
                WebviewClientPack clientPack = JsKit.jsKitAccess().getWebappInfoByUuid(UUID.fromString(newRegisteredJsAppUuidString));
                if (clientPack != null) {
                    Trace.verbose(TAG, "calling runOnAvailableActivityUiThread for onReady");
                    if (clientPack.mWebviewClient != null) {
                        JsKit.runOnAvailableActivityUiThread((WebappRunHost) clientPack.mWebviewClient.get(), new Runnable() {
                            public void run() {
                                Trace.verbose(JsKitAccessor.TAG, "calling signalWebappReady for ready event from runOnAvailableActivityUiThread run()");
                                String[] addresses = new String[]{bridge.getCurrentAddress()};
                                JsKit.jsKitAccess().signalWebappReady(addresses, JsKitAccessor.this.hostedWebappCallerId());
                            }
                        });
                    }
                }
            } catch (Exception e2) {
                Trace.debug(TAG, "signalAppScriptLoadedByBootstrap", e2);
            }
        }
        JsKit.jsKitAccess().signalAppScriptLoadedByBootstrap(hostedWebappCallerIdString(), externalRegisterWebappNeeded, newRegisteredJsAppUuidString);
    }

    @JavascriptInterface
    public String loadURL(String restrictedUrl) {
        if (restrictedUrl == null || (!restrictedUrl.toLowerCase().startsWith("http") && !restrictedUrl.toLowerCase().endsWith("html"))) {
            return JsKit.jsKitAccess().loadUrl(hostedWebappCallerIdString(), restrictedUrl, true);
        }
        return loadUrlNoBootstrap(restrictedUrl);
    }

    @JavascriptInterface
    public String loadUrlNoBootstrap(String restrictedUrl) {
        return JsKit.jsKitAccess().loadUrl(hostedWebappCallerIdString(), restrictedUrl, false);
    }

    @JavascriptInterface
    public void clientClose(String dataLeftBehind) {
        JsKit.jsKitAccess().clientClose(hostedWebappCallerIdString(), dataLeftBehind);
    }

    @JavascriptInterface
    public void clientClose(String dataLeftBehind, String overrideTagForData) {
        JsKit.jsKitAccess().clientClose(hostedWebappCallerIdString(), dataLeftBehind, overrideTagForData);
    }

    public String nativeSettingWrite(String settingName, String settingValue) {
        return JsKit.jsKitAccess().nativeSettingWrite(hostedWebappCallerIdString(), settingName, settingValue);
    }

    @JavascriptInterface
    public String nativeSettingWriteWithOptions(String settingName, String settingValue, String settingValueAndOptsJsonString) {
        return JsKit.jsKitAccess().nativeSettingWriteWithOptions(hostedWebappCallerIdString(), settingName, settingValue, settingValueAndOptsJsonString);
    }

    @JavascriptInterface
    public String nativeSettingRemove(String settingName) {
        return JsKit.jsKitAccess().nativeSettingRemove(hostedWebappCallerIdString(), settingName);
    }

    @JavascriptInterface
    public String nativeSettingRemoveWithOptions(String settingName, String settingValueAndOptsJsonString) {
        return JsKit.jsKitAccess().nativeSettingRemoveWithOptions(hostedWebappCallerIdString(), settingName, settingValueAndOptsJsonString);
    }

    @JavascriptInterface
    public String nativeSettingRead(String settingName) {
        return JsKit.jsKitAccess().nativeSettingRead(hostedWebappCallerIdString(), settingName);
    }

    @JavascriptInterface
    public String nativeSettingReadWithOptions(String settingName, String settingValueAndOptsJsonString) {
        return JsKit.jsKitAccess().nativeSettingReadWithOptions(hostedWebappCallerIdString(), settingName, settingValueAndOptsJsonString);
    }

    @JavascriptInterface
    public void privateFnConfirmReadySignal(boolean success) {
        JsKit.jsKitAccess().privateFnConfirmReadySignal(hostedWebappCallerIdString(), success);
    }

    @JavascriptInterface
    public void privateFnHeartbeatPeriodic() {
        JsKit.jsKitAccess().privateFnHeartbeatPeriodic(hostedWebappCallerIdString());
    }

    public void pong(String opt) {
        JsKit.jsKitAccess().pong(hostedWebappCallerIdString(), opt);
    }

    @JavascriptInterface
    public void privateFnSetProxyHtmlLocalStorageValue(String key, String value) {
        JsKit.jsKitAccess().privateFnSetProxyHtmlLocalStorageValue(key, value);
    }

    @JavascriptInterface
    public void privateFnResetProxyHtmlLocalStorage() {
        JsKit.jsKitAccess().privateFnResetProxyHtmlLocalStorage();
    }

    @JavascriptInterface
    public void privateFnLocalStorageWrite(String key, String value) {
        JsKit.jsKitAccess().localStorageWrite(hostedWebappCallerIdString(), key, value);
    }

    @JavascriptInterface
    public String privateFnLocalStorageRead(String key) {
        return JsKit.jsKitAccess().localStorageRead(hostedWebappCallerIdString(), key);
    }

    @JavascriptInterface
    public String privateFnLocalStorageReadAll() {
        return JsKit.jsKitAccess().localStorageRead(hostedWebappCallerIdString());
    }

    @JavascriptInterface
    public String privateFnLocalStorageReadAll_AtPreregistrationStage(String baseUriReference) {
        String newRegisteredJsAppUuidString = null;
        try {
            NoUiWebappBase appRef = (NoUiWebappBase) this.mHostedAndroidWebappRef.get();
            if (appRef != null) {
                newRegisteredJsAppUuidString = registerJavascriptAppinfo(appRef.loadAppInfoJsonAsString());
            }
            return JsKit.jsKitAccess().localStorageRead(newRegisteredJsAppUuidString);
        } catch (Exception e) {
            Trace.debug(TAG, "privateFnLocalStorageReadAll_AtPreregistrationStage", e);
            return "{}";
        }
    }

    @JavascriptInterface
    public void privateFnLocalStorageRemove(String key) {
        JsKit.jsKitAccess().localStorageRemove(hostedWebappCallerIdString(), key);
    }

    @JavascriptInterface
    public void privateFnLocalStorageClear() {
        JsKit.jsKitAccess().localStorageClear(hostedWebappCallerIdString());
    }

    @JavascriptInterface
    public void privateLog(String message) {
        Trace.verbose(TAG, "privateLog: " + message);
    }
}
